﻿/*
    This software is licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

    Copyright (C) 2010 Daniel Deptford (redmercury@gmail.com)
 
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be included in
        all copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        THE SOFTWARE.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Xml;

namespace COLLADASharp.Serialization
{
    public class DAESerializer
    {
        private static Dictionary<Type, ElementSerializerBase> staticElementSerializers = new Dictionary<Type, ElementSerializerBase>();
        private static Dictionary<Type, AttributeSerializerBase> staticAttributeSerializers = new Dictionary<Type, AttributeSerializerBase>();
        private static Dictionary<Type, TechniqueGroup> techniqueGroupsByType = new Dictionary<Type,TechniqueGroup>();
        private static ElementSerializerBase unregisteredTechniqueSerializer;
        private static ClassSerializer colladaSerializer = null;

        // Static intialization of all type mappings.
        static DAESerializer()
        {
            unregisteredTechniqueSerializer = CreateElementSerializer(typeof(TechniqueContainer.UnknownTechnique));
            staticElementSerializers.Add(typeof(TechniqueBase), new TechniqueElementSerializer());

            // Register all of the types in this assembly that have the [DAEClass] attribute
            Assembly thisAssembly = Assembly.GetExecutingAssembly();
            foreach (var type in thisAssembly.GetTypes())
            {
                if (!type.IsAbstract)
                {
                    if (typeof(DAENode).IsAssignableFrom(type) && GetElementSerializer(type) == null)
                    {
                        CreateElementSerializer(type);
                    }
                }
            }

            colladaSerializer = (ClassSerializer)GetElementSerializer(typeof(Core.COLLADA));
        }

        private class TechniqueRecord
        {
            public TechniqueRecord() { }

            public Type TechniqueType { get; set; }
            public string Profile { get; set; }
            public ElementSerializerBase ElementSerializer { get; set; }
        }

        private class TechniqueGroup
        {
            internal Dictionary<string, TechniqueRecord> techniquesByName = new Dictionary<string, TechniqueRecord>();
            internal Dictionary<Type, TechniqueRecord> techniquesByType = new Dictionary<Type, TechniqueRecord>();
            internal Type techniqueContainerType;

            public TechniqueGroup(Type techniqueContainerType)
            {
                this.techniqueContainerType = techniqueContainerType;
            }

            public void RegisterTechnique(Type techniqueType, string profile)
            {
                if (techniquesByName.ContainsKey(profile))
                {
                    throw new DAEException(string.Format("Technique container {0} already contains a technique named {1}, mapped to {2}", techniqueContainerType.Name, profile, techniquesByName[profile].TechniqueType.Name));
                }

                if (techniquesByType.ContainsKey(techniqueType))
                {
                    throw new DAEException(string.Format("Technique container {0} already contains a type {1} mapped to profile {2}", techniqueContainerType.Name, techniqueType.Name, techniquesByType[techniqueType].Profile ));
                }

                ElementSerializerBase elementSerializer = GetElementSerializer(techniqueType);
                if (elementSerializer == null)
                {
                    elementSerializer = CreateElementSerializer(techniqueType);
                }

                var record = new TechniqueRecord { Profile = profile, TechniqueType = techniqueType, ElementSerializer = elementSerializer };
                techniquesByName.Add(profile, record);
                techniquesByType.Add(techniqueType, record);
            }
        }

        public static void RegisterTechnique(Type techniqueCollectionType, Type techniqueType, string profile)
        {
            if (!typeof(TechniqueContainer).IsAssignableFrom(techniqueCollectionType))
            {
                throw new DAEException(string.Format("Type {0} is not a type of TechniqueContainer", techniqueCollectionType.Name));
            }

            if(!typeof(TechniqueBase).IsAssignableFrom(techniqueType))
            {
                throw new DAEException(string.Format("Type {0} is not a type of TechniqueBase", techniqueType.Name));
            }

            TechniqueGroup group = null;
            if (!techniqueGroupsByType.TryGetValue(techniqueCollectionType, out group))
            {
                group = new TechniqueGroup(techniqueCollectionType);
                techniqueGroupsByType.Add(techniqueCollectionType, group);
            }

            group.RegisterTechnique(techniqueType, profile);
        }

        internal ElementSerializerBase GetTechniqueSerializer(Type containingType, string profile)
        {
            TechniqueGroup group = techniqueGroupsByType[containingType];
            TechniqueRecord record = null;
            
            if (!group.techniquesByName.TryGetValue(profile, out record))
            {
                return unregisteredTechniqueSerializer;    
            }

            return record.ElementSerializer;
        }

        internal ElementSerializerBase GetTechniqueSerializer(Type containingType, Type techniqueType)
        {
            TechniqueGroup group = techniqueGroupsByType[containingType];
            TechniqueRecord record = null;

            if (!group.techniquesByType.TryGetValue(techniqueType, out record))
            {
                return unregisteredTechniqueSerializer;
            }

            return record.ElementSerializer;
        }

        internal string GetTechniqueProfile(Type containingType, Type techniqueType)
        {
            TechniqueGroup group = techniqueGroupsByType[containingType];
            TechniqueRecord record = null;

            if (!group.techniquesByType.TryGetValue(techniqueType, out record))
            {
                throw new DAEException(string.Format("Technique {0} is unknown", techniqueType.Name));
            }

            return record.Profile;
        }

        internal static ElementSerializerBase CreateElementSerializer(Type type)
        {
            ElementSerializerBase serializer = null;
            if (typeof(IDAESerializable).IsAssignableFrom(type))
            {
                serializer = new RawIDAESerializer(type);
            }
            else if (typeof(DAENode).IsAssignableFrom(type))
            {
                NodeProperty.InitializeForClass(type);
                serializer = new ClassSerializer(type);
            }
            else if (type.IsEnum)
            {
                serializer = new EnumElementSerializer(type);
            }
            else if (TypeDescriptor.GetConverter(type) != null)
            {
                serializer = new TypeConverterElementSerializer(type);
            }


            if (serializer == null)
            {
                throw new DAEException(string.Format("Could not create element serializer for type {0}", type));
            }

            staticElementSerializers.Add(type, serializer);
            serializer.Initialize();
            return serializer;
        }

        internal static AttributeSerializerBase CreateAttributeSerializer(Type type)
        {
            AttributeSerializerBase serializer = null;
            if (type.IsEnum)
            {
                serializer = new EnumAttributeSerializer(type);
            }
            else if (TypeDescriptor.GetConverter(type) != null)
            {
                serializer = new EnumAttributeSerializer(type);
            }

            if (serializer == null)
            {
                throw new DAEException(string.Format("Could not create attribute serializer for type {0}", type));
            }

            staticAttributeSerializers.Add(type, serializer);
            serializer.Initialize();
            return serializer;
        }

        internal static ElementSerializerBase GetElementSerializer(Type type)
        {
            ElementSerializerBase serializer = null;
            staticElementSerializers.TryGetValue(type, out serializer);
            return serializer;
        }

        internal static AttributeSerializerBase GetAttributeSerializer(Type type)
        {
            AttributeSerializerBase serializer = null;
            staticAttributeSerializers.TryGetValue(type, out serializer);
            return serializer;
        }

        public COLLADASharp.Core.COLLADA Deserialize(XmlReader reader)
        {
            reader.MoveToContent();
            if (reader.Name != "COLLADA")
                throw new DAEException("Root element is not COLLADA");

            return (COLLADASharp.Core.COLLADA)colladaSerializer.Deserialize(reader, null, this);
        }

        public COLLADASharp.Core.COLLADA Deserialize(string path)
        {
            using (Stream stream = new FileStream(path, FileMode.Open))
            {
                using (TextReader textReader = new StreamReader(stream))
                {
                    XmlReader reader = XmlReader.Create(textReader);
                    reader.MoveToContent();
                    if (reader.Name != "COLLADA")
                        throw new DAEException("Root element is not COLLADA");
                    return (COLLADASharp.Core.COLLADA)colladaSerializer.Deserialize(reader, null, this);
                }
            }
        }

        public void Serialize(COLLADASharp.Core.COLLADA collada, XmlWriter writer)
        {
        
        }

        public void Serialize(COLLADASharp.Core.COLLADA collada, string path)
        {
        
        }
    }

    internal abstract class ElementSerializerBase
    {
        public ElementSerializerBase() { }
        internal virtual void Initialize() { }
        public abstract object Deserialize(XmlReader reader, Type parentType, DAESerializer serializer);
        public abstract void Serialize(XmlWriter writer, object obj, DAESerializer serializer);
    }

    internal abstract class AttributeSerializerBase
    {
        public AttributeSerializerBase() { }
        internal virtual void Initialize() { }
        public abstract object Deserialize(XmlReader reader, string attributeName, DAESerializer serializer);
        public abstract void Serialize(XmlWriter writer, string attributeName, object obj, DAESerializer serializer);
    }
}
